﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using CSEdit.Server.Models;
using System.IO;
using System.Text;
using System.Net;

namespace CSEdit.Server.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        public IActionResult Editer(string path)
        {
            //DirectoryInfo d = Directory.CreateDirectory("");
            
            //ViewBag.Path = WebUtility.UrlEncode(Path.Combine("d:", "1.txt"));// "d:\\1.txt";
            ViewBag.Path = path;
            return View();
        }
        public async Task<IActionResult> GetFile(string path)
        {
            path = WebUtility.UrlDecode(path);
            //path = "d:\\1.txt";
            string r = string.Empty;
            using (var sr = new StreamReader(path, encoding: Encoding.UTF8))
            {
                r = await sr.ReadToEndAsync();
            }
            return Json(new { ret = 0, data = r });
        }
        public async Task<IActionResult> PostFile(string name, string data)
        {
            try
            {
                string path = "d:\\1.txt";
                FileInfo file = new FileInfo(path);
                using (StreamWriter sw = new StreamWriter(path, false, encoding: Encoding.UTF8))
                {
                    await sw.WriteAsync(data);
                }
                return Json(new { ret = 0 });
            }
            catch (Exception ex)
            {
                return Json(new { ret = 1, ex = ex.ToString() });
            }
        }
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
